package com.tuo51.foudation.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.StatusResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tuo51.foudation.model.ErrorCode.JSON_STR_ERROR;

/**
 * *******************************
 * Created by Ron.
 * form com.tuo51
 * on 2018/3/7
 * json 工具类
 * *******************************
 */
public class JsonUtil {
    public static ObjectMapper objectMapper = new ObjectMapper();

    public static String toJson(Object o){
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new BusinessException(JSON_STR_ERROR, "json转换出错");
        }
    }


    public static Map readToMap(String src) {
        Map map;
        try {
            map = objectMapper.readValue(src, HashMap.class);
        } catch (IOException e) {
            throw new BusinessException(JSON_STR_ERROR, "Json转Map出错");
        }
        return map;
    }

    public static List readToList(String src) {
        List map;
        try {
            map = objectMapper.readValue(src, List.class);
        } catch (IOException e) {
            throw new BusinessException(JSON_STR_ERROR, "Json转List出错");
        }
        return map;
    }
    public static <T> List<T> readListFormJson(String json, Class<T> clazz){
        try {
            JavaType javaType =objectMapper.getTypeFactory().constructParametricType(ArrayList.class, clazz);
            return objectMapper.readValue(json, javaType);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(JSON_STR_ERROR, "json转List<T> 对象出错");
        }
    }


    public static StatusResponse getResponse(String src, String errorMsg) {
        try {
            StatusResponse statusResponse = objectMapper.readValue(src, StatusResponse.class);
            if (statusResponse.getCode().equals(ErrorCode.UNDEFINED))
                throw new BusinessException(statusResponse.getCode(), errorMsg);
            if (!statusResponse.getCode().equals(ErrorCode.SUCCESSFUL))
                throw new BusinessException(statusResponse.getCode(), statusResponse.getMessage());
            return statusResponse;
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(JSON_STR_ERROR, errorMsg);
        }
    }

}
